<template>
  <div class="">
    <headMain :mensid="'2'" />
    <div class="mentactive">
      <div class="location">
        <img src="@/assets/images/location.png" alt="" />
      </div>
      <div>当前位置：</div>
      <div class="mentname1" @click="goback">病例学习></div>
      <div class="mentname1" @click="goback2" v-if="caseTypeName != '病例收藏'"
        >{{ caseTypeName }}></div
      >
      <div class="mentname2">{{ caseName }}</div>
    </div>

    <!-- 主题内容展示区域 -->
    <div class="casexqbox">
      <!-- 图像展示左区域 -->
      <div class="casexqleft">
        <!-- 显示图像区域 -->
        <div class="casecanvas" ref="casecanvas">
          <canvas
            class="myCanvaslxh"
            id="myCanvaslxh"
            :width="hbwidth"
            :height="hbheight"
            ref="canvasRef"
          ></canvas>
          <!-- 图像页码 -->
          <div class="casepagebox">
            第&nbsp;{{ findindex() + 1 }}&nbsp;页 共&nbsp;{{
              imgsrc.length
            }}&nbsp;页 &nbsp;图像数：{{ findindex() + 1 }}
          </div>
          <!-- 图像动态 -->

          <div
            class="casedtbox"
            @click="stopProcessing"
            v-if="processImagesflag"
          >
            <div class="casedticon tool">
              <img
                src="@/assets/images/play-circle-filled.png"
                alt=""
                class="normal"
              />
              <img
                src="@/assets/images/play-circle-filledac.png"
                alt=""
                class="active"
              />
            </div>
            暂停播放
          </div>
          <div class="casedtbox" @click="processImages" v-else>
            <div class="casedticon tool">
              <img
                src="@/assets/images/play-circle-filled.png"
                alt=""
                class="normal"
              />
              <img
                src="@/assets/images/play-circle-filledac.png"
                alt=""
                class="active"
              />
            </div>
            动态播放
          </div>
        </div>
        <!-- 图像功能区域 -->
        <div class="caselbox">
          <div class="caseleft tool" @click="tagdcoms(-1)">
            <img src="@/assets/images/caseleft.png" alt="" class="normal" />
            <img src="@/assets/images/caseleftac.png" alt="" class="active" />
          </div>
          <div
            class="caseimgbox beautifulScroll"
            ref="caseimglbox"
            @scroll="onScroll"
          >
            <div
              class="caseimgitem"
              v-for="(item, index) in imgsrc"
              :key="index"
              @click="tagdcom(item.caseImgId)"
            >
              <img :src="`${base + item.imgUrl}`" />
              <div class="msx" v-if="item.caseImgId == dcomid"></div
            ></div>
          </div>
          <div class="caseright tool" @click="tagdcoms(1)">
            <img src="@/assets/images/caseright.png" alt="" class="normal" />
            <img src="@/assets/images/caserightac.png" alt="" class="active" />
          </div>
        </div>
      </div>
      <!-- 图像详情右区域 -->
      <div class="casexqright">
        <div class="casexqitembox">
          <div class="casexqitemtitle">患者情况</div>
          <div class="casexqdesbox">{{ rendata.situation }}</div>
        </div>
        <div class="casexqitembox">
          <div class="casexqitemtitle">影像表现</div>
          <div class="casexqdesbox">{{ rendata.imgFeatures }}</div>
        </div>
        <div class="casexqitembox">
          <div class="casexqitemtitle">诊断结论</div>
          <div class="casexqdesbox">{{ rendata.diagnosticConclusion }}</div>
        </div>
      </div>

      <!-- 收藏区域 -->
      <div class="favbox" @click="favoritefn(favoriteFolderId)">
        <img
          src="@/assets/images/fa.png"
          alt=""
          v-if="favoriteFolderId != '0' && favoriteFolderId != null"
        />
        <img src="@/assets/images/faac.png" alt="" v-else />
        <div
          v-html="
            favoriteFolderId != '0' && favoriteFolderId != null
              ? '取消<br />收藏'
              : ' 收藏'
          "
        ></div>
      </div>
      <!-- 病例讨论 -->
      <div class="bltil" @click="freachfn">
        <img src="@/assets/images/bltl.png" alt="" /> <div>病例</div
        ><div>讨论</div>
      </div>
    </div>
    <!-- 病例讨论 -->
    <div class="caseimgdesboxs" v-if="caseshow">
      <div class="caseimgdest"
        >讨论（{{ discussListdata.length }}）
        <span @click="scrollToBottom">最新</span>
        <img
          @click="caseshow = false"
          src="@/assets/images/close-circle-filled.png"
          alt=""
          class="close"
        />
      </div>
      <div class="caseimgdeslist beautifulScroll" ref="caseImgDesList">
        <div class="caseimgdeslistitem" v-for="item in discussListdata">
          <div class="caseimguser">
            <img
              :src="base + studentdata.headPortraitUrl"
              alt=""
              v-if="studentdata.headPortraitUrl"
            />
            <img src="@/assets/images/1.png" alt="" v-else />
          </div>
          <div class="caseimglistright">
            <div class="casestu">{{ item.studentName }}</div>
            <div class="casecont">{{ item.content }}</div>
            <div class="casetimed">{{ item.createTime }}</div>
          </div>
        </div>
      </div>
      <div class="caseimgent">
        <div class="caseimguser">
          <img
            :src="base + studentdata.headPortraitUrl"
            alt=""
            v-if="studentdata.headPortraitUrl"
          />
          <img src="@/assets/images/1.png" alt="" v-else />
        </div>
        <div class="caseimginput">
          <input
            type="text"
            placeholder="说些什么"
            v-model="content"
            @keydown="handleEnter($event)"
          />
        </div>
        <div class="caseimgfs" @click="discussAddfn">
          <img src="@/assets/images/fasong.png" alt="" />
        </div>
      </div>
    </div>
  </div>
</template>

<script lang="ts" setup>
  import headMain from '@/views/headmain/index.vue';
  import {
    caseList,
    caserecordAdd,
    favoriteAdd,
    favoriteDel,
    caseDetails,
    discussList,
    discussAdd,
  } from '@/api/case';
  import { nextTick, onBeforeUnmount, onMounted, reactive, ref } from 'vue';
  import { useRouter } from 'vue-router';
  import { useRoute } from 'vue-router';
  import useUser from '@/hooks/user';
  import { storeToRefs } from 'pinia';
  import { Message, Modal, TreeNodeData } from '@arco-design/web-vue';
  import { useUserStore } from '@/store';
  const userStore = useUserStore();
  const userdata = storeToRefs(userStore);
  const studentdata = ref(userdata);
  const router = useRouter();
  const route = useRoute();
  const base = ref((window as any).config.VUE_APP_IMG_API);
  const caseTypeName = ref(route.query.caseTypeName);
  const caseTypeId = ref(route.query.caseTypeId);
  const caseName = ref(route.query.caseName);
  const caseId = ref(route.query.caseId);
  const favoriteStatus = ref(route.query.favoriteStatus);
  const favoriteFolderId = ref(route.query.favoriteFolderId);
  const total = ref();
  const pageSize = ref(6);
  const current = ref(1);
  const caseshow = ref(false);
  const rendata = ref({
    situation: '',
    imgFeatures: '',
    diagnosticConclusion: '',
  });
  const imgsrc = ref([]);
  const dcomid = ref('10');

  const fetchData = () => {
    caseDetails({
      studentId: studentdata.value.studentId,
      caseId: caseId.value,
    }).then((res: any) => {
      if (res.code == 200) {
        rendata.value = res.data;
        // console.log('病例详情完成', res.data);
        imgsrc.value = res.data.imgList;
        favoriteFolderId.value = res.data.favoriteFolderId;
        dcomid.value = imgsrc.value[0].caseImgId;
      }
    });
  };
  fetchData();
  // 病例添加记录
  const caseAdd = () => {
    caserecordAdd({
      studentId: studentdata.value.studentId,
      caseId: caseId.value,
    }).then((res: any) => {});
  };
  caseAdd();
  //   返回病例分类
  const goback = () => {
    router.push({
      name: 'casetype',
    });
  };
  const goback2 = () => {
    router.push({
      name: 'caselist',
      query: {
        caseTypeName: caseTypeName.value,
        caseTypeId: caseTypeId.value,
      },
    });
  };
  // 添加到收藏夹
  const favoritefn = (item) => {
    if (favoriteFolderId.value != '0' && favoriteFolderId.value != null) {
      favoriteDel({
        favoriteFolderIds: item,
      }).then((res: any) => {
        if (res.code == 200) {
          Message.success('取消收藏');

          fetchData();
        }
      });
    } else {
      favoriteAdd({
        studentId: studentdata.value.studentId,
        caseAtlasId: caseId.value,
        status: 0,
      }).then((res: any) => {
        if (res.code == 200) {
          Message.success('收藏成功');
          fetchData();
        }
      });
    }
  };

  // 定义画布高低
  const hbwidth = ref();
  const hbheight = ref();
  /// 引用 DOM 元素
  const casecanvas = ref<HTMLDivElement | null>(null);

  const canvasRef = ref<HTMLCanvasElement | null>(null);
  // 状态数据
  const state = reactive({
    img: new Image(),
    imgWidth: 389,
    imgHeight: 200,
    ctx: null as CanvasRenderingContext2D | null,
  });

  // 初始化
  onMounted(() => {
    hbwidth.value = casecanvas.value?.offsetWidth;
    hbheight.value = casecanvas.value?.offsetHeight;

    const canvas = canvasRef.value!;

    canvas.width = hbwidth.value;
    canvas.height = hbheight.value;
    canvas.addEventListener('wheel', handleWheel);
    // 获取 canvas 上下文
    state.ctx = canvas.getContext('2d');
    caseDetails({
      studentId: studentdata.value.studentId,
      caseId: caseId.value,
    }).then((res: any) => {
      if (res.code == 200) {
        rendata.value = res.data;

        imgsrc.value = res.data.imgList;
        dcomid.value = imgsrc.value[0].caseImgId;

        // 设置 canvas 尺寸

        // 加载图片
        state.img.src = base.value + imgsrc.value[0].imgUrl;
        state.img.onload = () => {
          state.imgWidth = state.img.naturalWidth;
          state.imgHeight = state.img.naturalHeight;
          draw(); // 图片加载完成后绘制
        };
      }
    });
  });
  onBeforeUnmount(() => {
    if (canvasRef.value) {
      canvasRef.value.removeEventListener('wheel', handleWheel);
    }
  });
  // 绘制函数
  const draw = () => {
    const canvas = canvasRef.value!;
    const ctx = state.ctx!;
    const img = state.img;

    ctx.clearRect(0, 0, canvas.width, canvas.height);

    // 设置缩放比例，这里设为 90% 的缩小比例
    const scale = 0.5;

    // 计算缩放后的宽度和高度
    const scaledWidth = img.naturalWidth * scale;
    const scaledHeight = img.naturalHeight * scale;

    // 计算居中绘制的偏移量
    const xOffset = (canvas.width - scaledWidth) / 2;
    const yOffset = (canvas.height - scaledHeight) / 2;

    // 绘制图片
    ctx.drawImage(img, xOffset, yOffset, scaledWidth, scaledHeight);
  };

  const tagdcom = (i: any) => {
    console.log('当前图像id', i);
    const imgsrcd = imgsrc.value.find((item: any) => item.caseImgId == i);

    dcomid.value = i;
    state.img.src = base.value + imgsrcd.imgUrl;
    state.img.onload = () => {
      state.imgWidth = state.img.width;
      state.imgHeight = state.img.height;
    };

    // }
    draw();
  };

  const findindex = () => {
    if (imgsrc.value.length < 0) {
      return;
    } else {
      return imgsrc.value.findIndex(
        (item: any) => item.caseImgId == dcomid.value
      );
    }
  };
  // 图像加载处理完成
  const caseimglbox = ref<HTMLElement | null>(null);

  const isAutoScrolling = ref(false); // 自动滚动标志
  const intervalId = ref<number | null>(null); // 存储定时器的 ID

  // 获取每个元素的宽度
  const getItemWidth = () => {
    const container = caseimglbox.value;
    const item = container?.querySelector('.caseimgitem');
    return item ? item.clientWidth : 0;
  };

  // 滚动到容器下一个 6 个元素
  const scrollToNext = () => {
    const container = caseimglbox.value;
    if (container) {
      const itemWidth = getItemWidth();
      const scrollWidth = itemWidth * 6; // 每次滚动 6 个元素的宽度
      container.scrollLeft += scrollWidth + 65; // 每次滚动 6 个元素的宽度
    }
  };

  // 启动自动滚动
  const startAutoScroll = () => {
    if (isAutoScrolling.value) return; // 防止多次启动
    isAutoScrolling.value = true;
    scrollToNext();
    // intervalId.value = setInterval(() => {
    //   scrollToNext();
    // }, 2000); // 每2秒滚动一次
  };

  // 停止自动滚动
  const stopAutoScroll = () => {
    if (intervalId.value) clearInterval(intervalId.value);
    intervalId.value = null;
    isAutoScrolling.value = false;
  };

  // 切换自动滚动状态
  const toggleAutoScroll = () => {
    if (isAutoScrolling.value) {
      stopAutoScroll();
    } else {
      startAutoScroll();
    }
  };

  // 监听滚动事件，暂停自动滚动
  const onScroll = () => {
    // 手动滚动时暂停自动滚动
    if (
      caseimglbox.value &&
      caseimglbox.value.scrollLeft <
        caseimglbox.value.scrollWidth - caseimglbox.value.clientWidth
    ) {
      stopAutoScroll(); // 手动滚动时暂停自动滚动
    }
  };

  // 停止处理函数
  const stopProcessing = () => {
    processImagesflag.value = false; // 设置为 false 停止循环
    if (timeoutId) {
      clearTimeout(timeoutId); // 清空定时器
    }
  };
  let timeoutId: NodeJS.Timeout | null = null; // 存储定时器I
  const processImagesflag = ref(false); // 控制是否继续执行的标志

  const processImages = () => {
    processImagesflag.value = true;
    // 使用 findIndex 查找匹配的元素，并获取其索引
    const targetIndex = imgsrc.value.findIndex(
      (src) => src.caseImgId === dcomid.value
    );

    // 如果找到了匹配的元素
    if (targetIndex !== -1 && processImagesflag.value) {
      // 从找到的索引开始，执行后续操作
      const processNext = (index: number) => {
        // 如果 processImagesflag 为 false，则停止继续执行
        if (!processImagesflag.value) {
          if (timeoutId) {
            clearTimeout(timeoutId); // 清空计时器
          }
          return; // 停止执行
        }

        // 如果当前索引在数组中有效
        if (index < imgsrc.value.length) {
          const src = imgsrc.value[index];

          // 判断当前的 index 是否符合特殊条件 7, 14, 21 等
          const isSpecialIndex = (index + 1) % 7 === 0;

          // 如果符合特殊条件，调用 toggleAutoScroll
          if (isSpecialIndex) {
            toggleAutoScroll();
          }

          // 执行 tagdcom
          tagdcom(src.caseImgId);

          // 延迟 1 秒后执行下一个循环
          timeoutId = setTimeout(() => {
            processNext(index + 1);
          }, 1000); // 1000 毫秒 = 1 秒
          // 如果索引已经到达数组的最后一个元素，设置 isProcessingComplete 为 true
          if (index === imgsrc.value.length - 1) {
            processImagesflag.value = false;
          }
        }
      };

      // 开始从找到的索引处执行
      processNext(targetIndex);
    }
  };

  const tagdcoms = (i: any) => {
    const index = imgsrc.value.findIndex(
      (item: any) => item.caseImgId == dcomid.value
    );
    if (i == 1) {
      if (imgsrc.value[index + 1]) {
        dcomid.value = imgsrc.value[index + 1].caseImgId;
        tagdcom(dcomid.value);

        console.log('执行了2', dcomid.value);
      }
    } else {
      if (imgsrc.value[index - 1]) {
        dcomid.value = imgsrc.value[index - 1].caseImgId;
        tagdcom(dcomid.value);

        console.log('执行了');
      }
    }
  };

  const handleWheel = (e: WheelEvent) => {
    e.preventDefault();
    if (e.deltaY < 0 && dcomid.value > '1') {
      tagdcoms(-1);
    } else {
      tagdcoms(1);
    }
  };

  // 病例讨论相关

  //   最新
  const caseImgDesList = ref();
  // 点击最新时滚动到最底部
  const scrollToBottom = () => {
    nextTick(() => {
      const listElement = caseImgDesList.value as HTMLElement;
      if (listElement) {
        listElement.scrollTop = listElement.scrollHeight;
      }
    });
  };
  // 发送讨论
  const content = ref('');
  const discussAddfn = () => {
    discussAdd({
      studentId: studentdata.value.studentId,
      caseId: caseId.value,
      content: content.value,
    }).then((res: any) => {
      if (res.code == 200) {
        freach();
        content.value = '';
      } else {
      }
    });
  };
  // 获取病例讨论
  const discussListdata = ref([]);
  const freachfn = () => {
    freach();
    caseshow.value = true;
  };
  const freach = () => {
    discussList({ caseId: caseId.value }).then((res: any) => {
      if (res.code == 200) {
        // console.log('查询成功', res.data);
        discussListdata.value = res.data.list;
      } else {
      }
    });
  };

  const handleEnter = (event) => {
    if (event.keyCode === 13) {
      // 回车键被按下，执行操作
      discussAddfn();
      // 这里可以放置触发的函数或逻辑
    }
  };
</script>

<style scoped>
  .mentactive {
    color: #666666;
    display: flex;
    align-items: center;
    font-size: 16px;
    margin-top: 40px;
    margin-left: 73px;
  }
  .location img {
    width: 16px;
    height: 16px;
  }
  .mentname1 {
    font-size: 22px;
    cursor: pointer;
  }
  .mentname2 {
    font-size: 22px;
    color: black;
  }
  .casexqbox {
    width: 1717px;
    height: 734px;
    background: #e8ebee;
    border-radius: 0px 0px 0px 0px;
    margin: 20px auto;
    display: flex;
    position: relative;
  }
  .casexqleft {
    height: 100%;
    background: #484c56;
    width: 846px;
    display: flex;
    flex-direction: column;
  }
  .casecanvas {
    width: 806px;
    height: 604px;
    background-color: black;
    margin: 20px auto;
    position: relative;
  }
  .casexqright {
    padding: 10px 0px;
    display: flex;
    flex-direction: column;
    width: 871px;
  }
  .casexqitembox {
    display: flex;
    flex-direction: column;
    margin: 5px auto;
    overflow: hidden;
  }
  .casexqitemtitle {
    font-size: 20px;
    color: #000000;
    margin: 15px 0;
  }

  .casexqdesbox {
    width: 800px;
    height: 166px;
    background: #ffffff;
    border: 1px solid #c5c5c5;
    overflow-y: auto;
    color: #666666;
    font-size: 16px;
    text-indent: 32px;
    padding: 20px 10px;
  }
  .favbox {
    width: 60px;
    height: 80px;
    background: #ffffff;
    border-radius: 0px 0px 0px 0px;
    position: absolute;
    right: -60px;
    top: 0px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    font-size: 14px;
    color: #666666;
    cursor: pointer;
  }
  .favbox img {
    text-align: center;
    display: block;
    width: 20px;
    height: 20px;
    margin: 5px 0;
  }
  .bltil {
    cursor: pointer;
    width: 60px;
    height: 109px;
    background: #ffffff;
    border-radius: 0px 0px 0px 0px;
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
    font-size: 14px;
    color: #666666;
    position: absolute;
    right: -60px;
    top: 85px;
  }
  .bltil img {
    display: block;
    width: 38px;
    height: 38px;
    margin: 5px 0;
  }
  .casepagebox {
    width: 225px;
    height: 36px;
    background: #1d1d1d;
    border-radius: 0px 0px 0px 0px;
    font-size: 16px;
    color: #ffff;
    display: flex;
    align-items: center;
    justify-content: center;
    position: absolute;
    left: 20px;
    bottom: 20px;
  }
  .casedtbox {
    display: flex;
    flex-direction: column;
    font-size: 14px;
    color: #ffff;
    position: absolute;
    right: 20px;
    bottom: 20px;
  }
  .caselbox {
    width: 808px;
    height: 70px;

    margin: 0 auto;
    display: flex;
  }
  .caseleft {
    width: 42px;
    height: 70px;
    background: #595e69;
    border-radius: 0px 0px 0px 0px;
    border: 1px solid #6c6c6c;
    display: flex;
    align-items: center;
    justify-content: center;
  }
  .caseright {
    width: 42px;
    height: 70px;
    background: #595e69;
    border-radius: 0px 0px 0px 0px;
    border: 1px solid #6c6c6c;
  }
  .caseimgbox {
    width: 704px;
    height: 70px;

    margin: 0px 10px;
    display: flex;
    overflow-y: auto;
  }
  .caseleft img {
    width: 31px;
    height: 31px;
  }
  .caseright img {
    width: 31px;
    height: 31px;
  }
  .caseimgitem {
    width: 64px;
    height: 70px;
    border-radius: 0px 0px 0px 0px;
    border: 1px solid rgba(255, 255, 255, 0.5);
    cursor: pointer;
    position: relative;
  }
  .caseimgitem img {
    width: 64px;
    height: 70px;
  }
  .myCanvaslxh {
    position: absolute;
    left: 50%;
    top: 50%;
    transform: translate(-50%, -50%);
  }
  .msx {
    position: absolute;
    width: 100%;
    height: 93%;
    border: 1px solid #fff;
    left: 1px;
    top: 1px;
  }
  .caseimgdesboxs {
    position: absolute;
    top: 65px;
    right: 0px;
    width: 421px;
    height: 100%;
    background: #ffffff;
    padding: 0px 20px;
    font-size: 28px;
    display: flex;
    align-items: center;
    flex-direction: column;
  }
  .caseimgdest {
    border-bottom: 1px solid #aaaaaa;
    height: 59px;
    width: 360px;
    display: flex;
    align-items: center;
    font-size: 20px;
    color: #666666;
  }
  .caseimgent {
    width: 361px;
    height: 50px;
    background: #eef1f4;
    border-radius: 10px;
    display: flex;
    align-items: center;
    position: absolute;
    bottom: 110px;
    padding: 10px;
  }
  .caseimguser {
    width: 40px;
    height: 40px;
    border-radius: 50%;
  }
  .caseimguser img {
    width: 40px;
    height: 40px;
  }
  .caseimginput {
    width: 390px;
    height: 50px;
    overflow: hidden;
    margin: 0px 10px;
  }
  .caseimginput input {
    font-size: 14px;
    width: 390px;
    height: 50px;
    background-color: #eef1f4;
  }
  .caseimgfs img {
    width: 30px;
    height: 30px;
    cursor: pointer;
  }
  .caseimgdeslist {
    overflow-y: auto;
    overflow-x: hidden;
    padding: 0px 10px;
    width: 100%;
    height: 75%;
    display: flex;
    flex-direction: column;
    padding-bottom: 30px;
  }
  .caseimgdeslistitem {
    display: flex;
    margin: 10px 0;
    align-items: center;
  }
  .caseimglistright {
    display: flex;
    flex-direction: column;
    margin: 0px 10px;
  }
  .casestu {
    font-size: 20px;
    color: #666666;
  }
  .casecont {
    width: 300px; /* 设置固定宽度 */
    white-space: nowrap; /* 防止文本换行 */
    overflow: hidden; /* 隐藏超出容器的部分 */
    text-overflow: ellipsis; /* 当文本超出时显示省略号 */
    font-size: 16px;
    margin: 5px 0;
  }
  .casetimed {
    font-size: 14px;
    color: #666666;
  }
  .caseimgdest span {
    color: #434e74;
    font-size: 20px;
    margin-left: 180px;
    display: block;
    cursor: pointer;
  }
  .close {
    width: 30px;
    height: 30px;
    cursor: pointer;
    margin: 0px 5px;
  }
</style>
